package geraltproject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;

import org.apache.commons.lang.StringUtils;

import dturner.com.*;

public class ListFileHandler {
  public final static String DEFAULT_PROC_PATH = "c:/temp/geraltproc";
  private String procPath = "";
  private String holdPath= "";
  
  public ListFileHandler() throws Exception
  {
    throw new Exception ("ListFileHandler not properly initialized");
  }
  
  public ListFileHandler(String origFilesPath, String procPath)
  {
    holdPath = origFilesPath;
    procPath = procPath;
  }
	
  public ListFileHandler(String origFilesPath)
  {
    procPath = DEFAULT_PROC_PATH;
    holdPath = origFilesPath;
  }
  
  
	public void processFiles() throws Exception
	{
	  // prepare processPath for processing
	  boolean exists = (new File(procPath)).exists(); 
	  boolean isKilled;
	  if (exists) 
	    isKilled = (new File(procPath)).delete(); 
	  
	  boolean success = (new File(procPath)).mkdir();
    if (success) {
      System.out.println("Directory: " + procPath + " created");
    }  
	  
	  // generate the files
	  String csvFileName = procPath + "/" + "bob.csv";
	  String errFileName = procPath + "/" + "error.txt";
	  
	  //String csvFileName = "bob.csv";
    //String errFileName = "error.txt";
	  Connection conn = getDBConnection();
    
	  File csvFile;
	  csvFile=new File(csvFileName);
	  csvFile.createNewFile();
    System.out.println("CSV file created");
    
    File errFile;
    errFile=new File(errFileName);
    errFile.createNewFile();
    System.out.println("Error file created");
    
    // read in files from the holding directory
    ArrayList<String> fileList = FileUtils.getTextFiles(holdPath);
    ArrayList<String> lineContent = new ArrayList<String>();
    for (int i=0;i< fileList.size();i++){
      File myFile = new File(fileList.get(i));
      System.out.println(myFile.getName());
      
      exists = (myFile.exists());
      if(!exists)
        throw new Exception("File to process does not exist");
      
      String loadCode =  StringUtils.replace(myFile.getName().toString(), ".txt", "").toUpperCase();
      
      // read inline of file
      FileInputStream fstream = new FileInputStream(myFile);
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      
      String strLine;
      System.out.println("Begin Adding files");
      while ((strLine = br.readLine()) != null)   {
        // Print the content on the console
        
        String[] contentArray =  StringUtils.split(strLine, " ");
        System.out.println("contentArray.length: " + contentArray.length);
        if(contentArray.length < 3){
          // write a row to errors
          writeRow(errFile,strLine );
        }else{
          // write a record to csv
          if(StringUtils.contains(contentArray[2], '@')){
            
            String sql = "insert into load_table (first_name, last_name, email, full_line, load_code) values (?,?,?,?,?)";
            
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, contentArray[0]);
            pstmt.setString(2, contentArray[1]);
            pstmt.setString(3, contentArray[2]);
            pstmt.setString(4, strLine);
            pstmt.setString(5, loadCode);
            
            pstmt.executeUpdate();
            pstmt.close();
          }else{
            // write a row to errors
            writeRow(errFile,strLine );
          }
        }
          
      }
      //Close the input stream
      in.close();
    } 
    System.out.println("End Processing");
    conn.close();
	} // end processFiles
	
	public void writeRow(File f, String s) throws Exception
	{
	  BufferedWriter writer = new BufferedWriter(
    new FileWriter(f,true)) ;
	  writer.newLine();
    writer.write(s) ;
    writer.flush();
    writer.close(); 	
	} // end writeRow
	
	public Connection getDBConnection() throws Exception
	{
	  String userName = "root";
    String password = "turner";
    String url = "jdbc:mysql://localhost:3306/geralt";
    Class.forName ("com.mysql.jdbc.Driver").newInstance ();
    Connection conn = DriverManager.getConnection (url, userName, password);
    System.out.println ("Database connection established");
    return conn;
	}
}
